package br.com.tiespec.ejb.Dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.tiespec.model.Enum.TipoSortOrder;
import br.com.tiespec.model.Modelo.Dado;
import br.com.tiespec.model.Util.DAOException;

@Stateless(mappedName = "DadoDAO")
public class DadoDAO extends DAO {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public List<Dado> listarDado(int first, int pageSize, String sortField,
			TipoSortOrder sortOrder, Long idDescricao) {
		List<Dado> aList = new ArrayList<Dado>();
		try {
			begin();
			Criteria criteria = this.session.createCriteria(Dado.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.add(Restrictions.eq("descricaoEstendida.id", idDescricao));
			criteria = montaPaginacaoSimples(criteria, first, pageSize, sortField, sortOrder);
			aList = criteria.list();
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return aList;
	}

	public Integer countDado(Long idDescricao) {
		Integer count = 0;
		try {
			begin();
			Criteria criteria = this.session.createCriteria(Dado.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.add(Restrictions.eq("descricaoEstendida.id", idDescricao))
					.setProjection(Projections.rowCount());
			count = Integer.parseInt(criteria.uniqueResult().toString());
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return count;
	}

	public Dado selecionar(Long id) {
		Dado aInstance = new Dado();
		try {
			begin();
			aInstance = (Dado) this.session.createCriteria(Dado.class)
					.add(Restrictions.eq("id", id)).uniqueResult();
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return aInstance;
	}

	public void excluir(Long id) throws DAOException {
		delete(Dado.class, id);
	}
	
}